const API_BASE_URL = 'http://localhost:3000/api';

// 通用请求函数
async function request(endpoint, options = {}) {
  const url = `${API_BASE_URL}${endpoint}`;
  
  const defaultOptions = {
    headers: {
      'Content-Type': 'application/json',
    },
  };

  const config = {
    ...defaultOptions,
    ...options,
    headers: {
      ...defaultOptions.headers,
      ...options.headers,
    },
  };

  try {
    const response = await fetch(url, config);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('API请求失败:', error);
    throw error;
  }
}

// 成员相关API
export const memberAPI = {
  // 获取所有成员
  async getAllMembers() {
    const response = await request('/persons');
    return response.data || [];
  },

  // 获取单个成员详情
  async getMemberDetails(id) {
    const response = await request(`/persons/${id}`);
    return response.data;
  },

  // 添加成员
  async addMember(memberData) {
    const response = await request('/persons', {
      method: 'POST',
      body: JSON.stringify(memberData),
    });
    return response.data;
  },

  // 更新成员
  async updateMember(id, memberData) {
    const response = await request(`/persons/${id}`, {
      method: 'PUT',
      body: JSON.stringify(memberData),
    });
    return response.data;
  },

  // 删除成员
  async deleteMember(id) {
    const response = await request(`/persons/${id}`, {
      method: 'DELETE',
    });
    return response;
  },
};

// 家谱树相关API
export const familyTreeAPI = {
  // 获取家谱树结构
  async getFamilyTree() {
    const response = await request('/persons/tree');
    return response.data || [];
  },
};

// 登录API
export async function loginAPI(username, password) {
  return await request('/login', {
    method: 'POST',
    body: JSON.stringify({ username, password })
  });
}

export default {
  memberAPI,
  familyTreeAPI,
}; 